<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import * as monaco from 'monaco-editor';
import type { ProblemVO } from '@/api/Problem.ts';
import { ProblemApi } from '@/api/ProblemApi.ts';
import InfoTab from './components/InfoTab.vue';
import SubmissionTab from './components/submissionTab.vue';

// 通过 props 接收路由参数
const props = defineProps<{
  id: string;
}>();

const route = useRoute();

// 题目数据
const problemData = ref<ProblemVO | null>(null);
const loading = ref(false);

// 标签页
const activeTab = ref('info');

const editorContainer = ref<HTMLElement | null>(null);
let editor: monaco.editor.IStandaloneCodeEditor | null = null;

// 加载题目数据
const loadProblemData = async () => {
  loading.value = true;
  try {
    const data = await ProblemApi.getProblem(props.id);
    problemData.value = data;
    console.log('题目数据加载成功:', data);
  } catch (error: any) {
    console.error('加载题目失败:', error);
    message.error(error.message || '加载题目失败');
  } finally {
    loading.value = false;
  }
};

// 语言选择
const selectedLanguage = ref<'cpp' | 'java' | 'python'>('cpp');

// 提交状态
const submitting = ref(false);

// 语言选项
const languageOptions = [
  { value: 'cpp', label: 'C++' },
  { value: 'java', label: 'Java' },
  { value: 'python', label: 'Python' },
];

// 各语言的模板代码
const codeTemplates = {
  cpp: `#include <iostream>
using namespace std;

int main() {
    // 在这里编写你的代码

    return 0;
}`,
  java: `public class Main {
    public static void main(String[] args) {
        // 在这里编写你的代码

    }
}`,
  python: `def main():
    # 在这里编写你的代码
    pass

if __name__ == "__main__":
    main()`,
};

// 语言映射到 Monaco Editor 的语言标识
const monacoLanguageMap = {
  cpp: 'cpp',
  java: 'java',
  python: 'python',
};

onMounted(async () => {
  // 加载题目数据
  await loadProblemData();

  // 初始化编辑器
  if (editorContainer.value) {
    editor = monaco.editor.create(editorContainer.value, {
      value: codeTemplates[selectedLanguage.value],
      language: monacoLanguageMap[selectedLanguage.value],
      theme: 'vs-dark',
      automaticLayout: true,
      fontSize: 14,
      minimap: { enabled: true },
      scrollBeyondLastLine: false,
    });
  }
});

onBeforeUnmount(() => {
  editor?.dispose();
});

// 监听语言切换
watch(selectedLanguage, (newLang) => {
  if (editor) {
    const currentCode = editor.getValue();
    const templateCode = codeTemplates[newLang];

    // 如果当前代码是模板代码，则切换到新语言的模板
    const isTemplateCode = Object.values(codeTemplates).some(
      (template) => currentCode.trim() === template.trim()
    );

    if (isTemplateCode || !currentCode.trim()) {
      editor.setValue(templateCode);
    }

    // 更新编辑器语言
    monaco.editor.setModelLanguage(editor.getModel()!, monacoLanguageMap[newLang]);
  }
});

const handleSubmit = async () => {
  if (!editor) {
    message.error('编辑器未初始化');
    return;
  }

  const code = editor.getValue();
  if (!code.trim()) {
    message.warning('请输入代码');
    return;
  }

  if (!problemData.value?.id) {
    message.error('题目信息未加载');
    return;
  }

  try {
    submitting.value = true;
    const result = await ProblemApi.doProblem({
      problemId: problemData.value.id,
      code: code,
      language: selectedLanguage.value,
    });

    message.success(`提交成功！`);
    // 提交成功后切换到提交记录标签页
    activeTab.value = 'submissions';
  } catch (error: any) {
    message.error(error.message || '提交失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};
</script>

<template>
  <div class="w-full h-full flex gap-5 p-5 bg-gray-50/30">
    <!-- 题目内容卡片 - 使用标签页 -->
    <div class="problem-card w-1/2 h-full flex flex-col bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
      <a-tabs v-model:activeKey="activeTab" class="h-full flex flex-col [&_.ant-tabs-nav]:pl-5">
        <a-tab-pane key="info" tab="题目详情" class="h-full">
          <InfoTab :problemData="problemData" :loading="loading" />
        </a-tab-pane>
        <a-tab-pane key="submissions" tab="提交记录" class="h-full">
          <SubmissionTab :problemId="props.id" />
        </a-tab-pane>
      </a-tabs>
    </div>

    <!-- 代码编辑器卡片 -->
    <div class="editor-card w-1/2 h-full flex flex-col bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
      <!-- 编辑器头部 -->
      <div class="editor-header px-5 py-3.5 border-b border-gray-100 bg-gradient-to-r from-white to-gray-50/50">
        <div class="flex items-center gap-3">
          <span class="text-sm text-gray-600">选择语言：</span>
          <a-select
            v-model:value="selectedLanguage"
            :options="languageOptions"
            size="small"
            class="w-28"
          />
        </div>
      </div>

      <!-- 编辑器区域 -->
      <div ref="editorContainer" class="flex-1 overflow-hidden"></div>

      <!-- 提交按钮区域 -->
      <div class="submit-area px-5 py-3.5 border-t border-gray-100 bg-gray-50/50 flex items-center justify-end">
        <a-button
          type="primary"
          size="large"
          :loading="submitting"
          :disabled="submitting"
          @click="handleSubmit"
          class="px-8 h-10 rounded-lg shadow-sm hover:shadow-md transition-all duration-200"
        >
          <span class="font-medium">{{ submitting ? '提交中...' : '提交代码' }}</span>
        </a-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Tabs 内容高度样式 */
:deep(.ant-tabs-content) {
  height: 100%;
  overflow: hidden;
}

:deep(.ant-tabs-content-holder) {
  overflow: hidden;
}

:deep(.ant-tabs-tabpane) {
  height: 100%;
  overflow: hidden;
}

/* 按钮悬浮效果优化 */
button {
  user-select: none;
}
</style>
